<template>
  <page-meta :root-font-size="rootFontSize() + 'px'"></page-meta>

  <view v-if="isVisible">
    <web-view :src="`https://nlh5.cheeseword.com/h5/#/webview/shareDiploma?params=${params}`" />
  </view>

  <view v-if="!isVisible" class="page-container">
    <image class="image-wrapper" mode="widthFix" :src="dataURL" />
  </view>

  <CwCommon />
</template>

<script setup lang="ts">
import { ref, nextTick } from 'vue';
import { onLoad } from "@dcloudio/uni-app";
import { rootFontSize, util } from "@/utils/util";
import API from "@/api";

const dataURL = ref("");
const filePath = ref("");
const params = ref("");
const isVisible = ref(true);
const day_num = ref("0");
const course_id = ref("0");
const share_reward = ref(0);

onLoad(async (option: any) => {
  params.value = option.data;

  if (option.data) {
    const temp = JSON.parse(decodeURIComponent(option.data));

    day_num.value = temp.day_num;
    course_id.value = temp.course_id;
    share_reward.value = Number(temp.share_reward);
  }

  if (option.dataURL && option.dataURL.length) {
    dataURL.value = option.dataURL;
    handleShareImageMenu();
  }
});

const handleCancelAuth = () => {
  util.showDialogue("获取相册授权失败");

  setTimeout(() => {
    isVisible.value = true;
  }, 1000);
};

const handleConfirmAuth = () => {
  uni.openSetting({
    success: (res: any) => {
      if (res.authSetting["scope.writePhotosAlbum"]) {
        handleShareImageMenu();
      } else {
        util.showDialogue("获取相册授权失败");
      }
    },
    fail: () => {
      util.showDialogue("获取相册授权失败");
    },
    complete: () => {
      setTimeout(() => {
        isVisible.value = true;
      }, 1000);
    }
  });
};

const base64ToBuffer = (base64data: string, callback?: Function) => {
  const regex = /data:image\/(\w+);base64,(.*)/;
  const [, format, bodyData] = regex.exec(base64data) || [];

  if (!format) {
    return new Error("ERROR_BASE64SRC_PARSE");
  }
  const fsm = wx.getFileSystemManager();
  const buffer = wx.base64ToArrayBuffer(bodyData);
  const FILE_BASE_NAME = new Date().getTime();
  const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${format}`;

  fsm.writeFile({
    filePath,
    data: buffer,
    encoding: "binary",
    success: () => {
      callback && callback(filePath);
    },
    fail: () => {
      callback && callback("");
    }
  });
};

const handleSetFilePath = () => {
  return new Promise((resolve, reject) => {
    if (filePath.value) {
      return resolve(filePath.value);
    }
    const isiOS = ["ios", "mac"].includes(uni.getSystemInfoSync().platform);

    if (isiOS) {
      base64ToBuffer(dataURL.value, (localUrl: string) => {
        if (localUrl.length) {
          filePath.value = localUrl;
          return resolve(localUrl);
        }
        return reject();
      });
    } else {
      const times = new Date().getTime();
      const tempPath = wx.env.USER_DATA_PATH + "/" + times + ".png";

      uni.getFileSystemManager().writeFile({
        filePath: tempPath,
        data: dataURL.value.slice(22),
        encoding: "base64",
        success: () => {
          filePath.value = tempPath;
          resolve(tempPath);
        },
        fail: () => {
          filePath.value = "";
          resolve("");
        },
      });
    }
  })
};

const handleShareImageMenu = async () => {
  const filePath = await handleSetFilePath() as string;

  wx.showShareImageMenu({
    path: filePath,
    style: "v2",
    success: (res: { errMsg: string }) => {
      if (res.errMsg === "showShareImageMenu:ok" && share_reward.value !== 0) {
        API.shareRecord({
          "type": 17,
          "shareType": 1,
          day_num: day_num.value,
          course_id: course_id.value,
        }).then(async () => {
          isVisible.value = false;
          share_reward.value = 0;

          const temp = JSON.parse(decodeURIComponent(params.value));
          temp.share_reward = 0;
          params.value = encodeURIComponent(JSON.stringify(temp));

          await nextTick();
          setTimeout(() => {
            isVisible.value = true;
          }, 150);
        })
      }
    },
    fail: async (err: { errMsg: string }) => {
      if (err.errMsg === "showShareImageMenu:fail auth deny") {
        isVisible.value = false;
        await nextTick();

        util.showModal({
          isShowModal: true,
          title: "检测到您没打开相册功能权限，是否去设置打开？",
          success: () => handleConfirmAuth(),
          cancel: () => handleCancelAuth(),
        })
      }
    },
  });
};
</script>

<style scoped lang="scss">
.page-container {
  width: 100vw;
  height: 100vh;
  background-color: #ffd388;

  .image-wrapper {
    width: 37.5rem;
    margin-left: 50%;
    transform: translateX(-50%);
  }
}
</style>
